package test.controller;

import jdbc.InputUtil;
import test.mapper.ArticleMapper;
import test.vo.Article;

import java.util.List;
import java.util.Scanner;

public class ArticleController {
    private ArticleMapper articleMapper = new ArticleMapper();
    public static void main(String[] args) {
        ArticleController articleController = new ArticleController();
        articleController.start();
    }

    public void start(){
        a:while(true){
            System.out.println("欢迎来到文章管理系统");
            System.out.println("请输入操作编号");
            System.out.println("1:保存文章");
            System.out.println("2:删除文章");
            System.out.println("3:查询指定文章");
            System.out.println("4:查询所有文章");
            System.out.println("5:退出");
            Scanner scan = new Scanner(System.in);
            String number = scan.nextLine();
            switch(number){
                case "1":
                    writeArticle();
                    break;
                case "2":
                    removeArticle();
                    break;
                case "3":
                    showArticle();
                    break;
                case "4":
                    showAllArticle();
                    break;
                case "5":
                    System.out.println("再见!");
                    //return;
                    break a;
                default:
                    System.out.println("输入有误");
            }
        }
    }
    //发表文章功能
    public void writeArticle(){
        //提示用户输入文章信息
        Article article = InputUtil.getInputObject(new Article(),"发表文章");
        //调用ArticleMapper将文章保存
        int num = articleMapper.insertArticle(article);
        //根据保存结果提示用户是否成功
        if(num>0){
            System.out.println("文章发表成功");
        }else{
            System.out.println("文章发表失败");
        }
    }
    public void removeArticle(){
        System.out.println("删除文章");
        System.out.println("请输入要删除的文章id");
        Scanner scanner = new Scanner(System.in);
        int id = Integer.parseInt(scanner.nextLine());
        int num = articleMapper.deleteArticleById(id);
        System.out.println(num>0?"删除成功":"删除失败");
    }
    public void showArticle(){
        System.out.println("查询文章");
        System.out.println("请输入要查询的文章id");
        Scanner scanner = new Scanner(System.in);
        int id = Integer.parseInt(scanner.nextLine());
        Article article = articleMapper.findById(id);
        System.out.println("标题:"+article.getTitle());
        System.out.println("正文:"+article.getContent());
    }

    public void showAllArticle(){
        List<Article> articles = articleMapper.findAll();
        for(Article article : articles){
            System.out.println("标题:"+article.getTitle());
            System.out.println("正文:"+article.getContent());
            System.out.println();
        }
    }
}
